﻿using System;
using System.Threading.Tasks;
using System.Threading;

namespace WatchDog.WinService
{
    public class DelayedTask
    {
        private readonly CancellationTokenSource cts1 = new();
        private readonly CancellationToken token = new();
        public DelayedTask(int millisecondsDelay, Func<Task> func)
        {
            token = cts1.Token;
            IsCompleted = true;
            MillisecondsDelay = millisecondsDelay;

            Task.Run(async () =>
            {
                await Task.Delay(millisecondsDelay, token);
                if (!token.IsCancellationRequested)
                {
                    await func();
                }
                else
                {
                    //取消
                }
                IsCompleted = true;
            }, token);
        }

        public void Cancel()
        {
            cts1.Cancel();
        }

        public int MillisecondsDelay { get; private set; }
        public bool IsCompleted { get; private set; }
    }

}
